# _*_ coding:utf-8 _*_
# @author : Joyamon
# @time : 2022-10-10 16:47
# @file : youdao_translate.py


from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
import time


def search_youdao():
    return input('有道翻译为您提供服务，请输入要翻译的单词（句子）：')


class Youdao:
    def __init__(self):
        # 设置成无头浏览器
        chrome_option = Options()
        chrome_option.add_argument('--headless')
        self.driver = webdriver.Chrome(options=chrome_option)

        url = 'https://fanyi.youdao.com/'
        self.driver.get(url)

    def translate_youdao(self, keywords):
        self.driver.find_element(By.CSS_SELECTOR,
                                 'body > div.fanyi__nav > div > ul > li.nav__rengong > div > a.i-know').click()
        self.driver.find_element(By.ID, 'inputOriginal').clear()
        self.driver.find_element(By.ID, 'inputOriginal').send_keys(keywords)
        self.driver.find_element(By.ID, 'transMachine').click()
        time.sleep(0.5)
        try:
            a = self.driver.find_element(By.XPATH, "//div[@id='transTarget']/p/span")
            if a.text:
                print(f'翻译结果：{a.text}')
            else:
                pass
        except:
            print('抱歉，我还在学习该语种中...')

        self.driver.close()
